package com.login.listener;

import com.login.cache.LoginCache;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class LoginSessionListener implements HttpSessionAttributeListener {

    private static String USER_NAME = "username";

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        String attrName = se.getName();

        // 如果此时向 session 中添加的属性值是 USER_NAME
        if (USER_NAME.equals(attrName)) {
            String attrValue = (String) se.getValue();
            HttpSession session = se.getSession();
            String sessionId = session.getId();

            LoginCache loginCache = LoginCache.getInstance();
            String prevSessionId = loginCache.getSessionIdByUsername(attrValue);
            if (prevSessionId == null) { // 第一次登录

            } else { // 清除原来的 sessionId 对应的 session 数据
                HttpSession prevSession = loginCache.getSessionBySessionId(prevSessionId);
                prevSession.invalidate();
            }
            loginCache.setSessionIdByUserName(attrValue, sessionId);
            loginCache.setSessionBySessionId(sessionId, session);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {

    }
}
